﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace XamlDev.ServiceLocatorPattern.Client
{
    public class ServiceLocator
    {
        private static readonly Dictionary<string, object> services = new Dictionary<string, object>();

        #region Basic Impl
        public static void SetService<TInterface>(TInterface t)
        {
            services.Add(typeof(TInterface).FullName, t);
        }

        public static TInterface GetService<TInterface>()
        {
            return (TInterface)services[typeof(TInterface).FullName];
        }
        #endregion

        #region Regular Impl
        public static void SetService<TInterface>(string key, TInterface t)
        {
            services.Add(key, t);
        }

        public static TInterface GetService<TInterface>(string key)
        {
            return (TInterface)services[key];
        }
        #endregion

        #region Advanced Impl

        public static void RegisterServiceFromAppSettings<T>(string appSettingsKey)
        {
            var fullTypeName = ConfigurationManager.AppSettings[appSettingsKey];
            var serviceType = Type.GetType(fullTypeName, true);
            var serviceInstance = (T)Activator.CreateInstance(serviceType);
            ServiceLocator.SetService<T>(serviceInstance);
        }

        #endregion
    }
}
